import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core';
import { PageHeaderModule } from '@delon/abc/page-header';
import { STColumn, STModule } from '@delon/abc/st';
import { ModalHelper, _HttpClient } from '@delon/theme';
import { NzBreadCrumbModule } from 'ng-zorro-antd/breadcrumb';
import { NzButtonModule } from 'ng-zorro-antd/button';
import { NzDrawerModule } from 'ng-zorro-antd/drawer';
import { NzIconModule } from 'ng-zorro-antd/icon';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzTypographyComponent } from 'ng-zorro-antd/typography';
import { Api } from 'src/app/shared/api';
import { ImagePreviewComponent } from 'src/app/shared/preview/image-preview';
import { PdfPreviewComponent } from 'src/app/shared/preview/pdf-reader';
import { TextPreviewComponent } from 'src/app/shared/preview/text-preview';
import { VjsPlayerComponent } from 'src/app/shared/preview/vedio-js-player';
import { ResponseCode } from 'src/app/shared/response.code';
import { NzDownloadModalComponent } from 'src/app/shared/widget/download.widget';

import { FolderComponent } from './folder.conponent';
import { UploadComponent } from './upload.component';

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  changeDetection: ChangeDetectionStrategy.Default,
  standalone: true,
  imports: [
    PageHeaderModule,
    NzButtonModule,
    NzBreadCrumbModule,
    STModule,
    NzIconModule,
    ImagePreviewComponent,
    NzDrawerModule,
    VjsPlayerComponent,
    PdfPreviewComponent,
    TextPreviewComponent,
    NzTypographyComponent
  ]
})
export class DashboardComponent implements OnInit {
  page: any = { show: false };
  visibleDraw: boolean = false;
  currentPreview: any = { name: '预览' };
  // TODO 当前版本未实现批量操作
  showFileControl: any = { group: false, rename: false, download: false, prview: false, edit: false };
  data: any[] = [];
  nodeLevel: any[] = [];
  fileType: { [key: string]: any } = {
    folder: 'folder',
    excel: 'file-excel',
    word: 'file-word',
    ppt: 'file-ppt',
    pdf: 'file-pdf',
    image: 'file-image',
    gif: 'file-gif',
    video: 'video-camera',
    sound: 'sound',
    text: 'file-text',
    zip: 'file-zip',
    unknown: 'file-unknown'
  };
  constructor(
    private http: _HttpClient,
    private modal: ModalHelper,
    private msg: NzMessageService
  ) {}

  ngOnInit() {
    this.getUserNode('0');
  }

  // @ViewChild('st', { static: false }) private st!: STComponent;
  columns: STColumn[] = [
    // { index: 'id.value', type: 'checkbox' },
    { render: 'type', width: 50 },
    { title: '文件名', render: 'name', sort: true },
    { title: '预览', render: 'preview', width: 100 },
    { title: '大小', render: 'size', width: 150, sort: true },
    // { title: '拥有者', index: 'owner' ,width: 150, sort: true},
    {
      width: 200,
      buttons: [
        {
          icon: 'download',
          iif: record => this.canDownload(record),
          type: 'modal',
          modal: {
            params: (record: any) =>
              (record = { url: `${Api.BaseNodeApi}/download?id=${record.id}`, filename: record.path ? record.name : `${record.name}.zip` }),
            component: NzDownloadModalComponent,
            modalOptions: { nzClosable: false, nzMask: true, nzTitle: '下载中……', nzMaskClosable: false },
            size: 'sm'
          }
        },
        {
          icon: 'eye',
          iif: record => this.canPreview(record),
          click: record => this.preview(record)
        },
        {
          icon: 'delete',
          type: 'del',
          iif: record => this.canEdit(record),
          click: record => this.delete(record)
        }
        // TODO 以下功能此版本暂不实现
        // {
        //   icorn: 'more',
        //   iif:(record)=>this.canEdit(record),
        //   children: [
        //     {
        //       text: '复制到',
        //       click: e => this.copy(),
        //     },
        //     {
        //       text: `移动到`,
        //       click: e => this.move(),
        //     },
        //     {
        //       text: '重命名',
        //       click: e => this.rename(),
        //     },
        //     {
        //       text: '转让',
        //       click: e => this.change(),
        //     }
        //   ],
        // },
      ]
    }
  ];

  getUserNode(parentId: string) {
    let params = { parentId: parentId };
    this.http.get(`${Api.BaseNodeApi}/node`, params).subscribe(res => {
      if (res.code === ResponseCode.SUCCESS) {
        this.data = res.data;
      } else {
        this.msg.error(res.message ? res.message : '获取用户文件失败');
      }
    });
  }

  canDownload(record: any): boolean {
    // TODO 判断下载权限
    return true;
  }

  canPreview(record: any): boolean {
    // TODO 判断预览权限
    if (record.type === 'folder' || record.type == 'image' || record.type == 'unknown' || record.type == 'zip') {
      return false;
    }
    return true;
  }

  canEdit(record: any): boolean {
    // TODO 判断编辑权限
    return true;
  }

  getFileType(type: string): string {
    const icon = this.fileType[type];
    return icon ? icon : this.fileType['unknown'];
  }

  getFileSize(type: string, size: number): string {
    if (type === 'folder') return '-';
    if (size) {
      if (size > 1024 * 1024 * 1024 * 1024) {
        return `${(size / 1024 / 1024 / 1024 / 1024).toFixed(2)}TB`;
      } else if (size > 1024 * 1024 * 1024) {
        return `${(size / 1024 / 1024 / 1024).toFixed(2)}GB`;
      } else if (size > 1024 * 1024) {
        return `${(size / 1024 / 1024).toFixed(2)}MB`;
      } else if (size > 1024) {
        return `${(size / 1024).toFixed(2)}KB`;
      } else {
        return `${size}B`;
      }
    }
    return '-';
  }

  rowChange(event: any) {
    if (event && event.type === 'checkbox') {
      if (event.checkbox && event.checkbox.length > 0) {
        this.showFileControl.group = true;
        if (event.checkbox.length > 1) {
          this.showFileControl.rename = true;
        } else {
          this.showFileControl.rename = false;
          if (event.checkbox[0].type === 'folder') {
            this.showFileControl.preview = true;
          } else {
            this.showFileControl.preview = false;
          }
          this.showFileControl.download = false;
          this.showFileControl.edit = false;
        }
      } else {
        this.showFileControl.group = false;
        this.showFileControl.rename = false;
      }
    }
    if (event && event.type === 'sort') {
      console.log(`按照${event.sort.column.indexKey}进行${event.sort.value}排序`);
    }
    console.log(event);
  }

  intoNode(record: any) {
    console.log(record);
    if (record.type === 'folder') {
      let exit = this.nodeLevel.filter(item => item.id === record.id);
      if (exit.length) {
        let tmp = [];
        for (let i = 0; i < this.nodeLevel.length; i++) {
          tmp.push(this.nodeLevel[i]);
          if (this.nodeLevel[i].id === record.id) break;
        }
        this.nodeLevel = tmp;
      } else {
        this.nodeLevel.push(record);
      }
      this.getUserNode(record.id);
    } else {
      this.msg.info('点中了文件哦');
    }
  }

  prevFolder() {
    if (this.nodeLevel.length == 1) {
      this.getUserNode('0');
      this.nodeLevel = [];
      return;
    }
    this.intoNode(this.nodeLevel[this.nodeLevel.length - 2]);
  }

  addFolder() {
    let parentId = '0';
    if (this.nodeLevel.length) {
      parentId = this.nodeLevel[this.nodeLevel.length - 1].id;
    }
    this.modal.createStatic(FolderComponent, { parentId: parentId }).subscribe(() => {
      if (this.nodeLevel.length > 0) {
        this.getUserNode(this.nodeLevel[this.nodeLevel.length - 1].id);
      } else {
        this.getUserNode('0');
      }
    });
  }

  uploadFile() {
    let parentId = '0';
    if (this.nodeLevel.length) {
      parentId = this.nodeLevel[this.nodeLevel.length - 1].id;
    }
    this.modal.createStatic(UploadComponent, { parentId: parentId }).subscribe(() => {
      if (this.nodeLevel.length > 0) {
        this.getUserNode(this.nodeLevel[this.nodeLevel.length - 1].id);
      } else {
        this.getUserNode('0');
      }
    });
  }

  preview(record: any) {
    this.currentPreview = record;
    this.visibleDraw = true;
  }

  closeDraw() {
    this.currentPreview = { name: '预览' };
    this.visibleDraw = false;
  }

  delete(record: any) {
    let params = { id: record.id };
    if (record.type === 'folder') {
      this.http.delete(`${Api.BaseNodeApi}/folder`, params).subscribe(res => {
        if (res.code === ResponseCode.SUCCESS) {
          this.msg.success('删除成功');
          if (this.nodeLevel.length > 0) {
            this.getUserNode(this.nodeLevel[this.nodeLevel.length - 1].id);
          } else {
            this.getUserNode('0');
          }
        } else {
          this.msg.error(res.message ? res.message : '删除失败！');
        }
      });
    } else {
      this.http.delete(Api.BaseNodeApi, params).subscribe(res => {
        if (res.code === ResponseCode.SUCCESS) {
          this.msg.success('删除成功');
          if (this.nodeLevel.length > 0) {
            this.getUserNode(this.nodeLevel[this.nodeLevel.length - 1].id);
          } else {
            this.getUserNode('0');
          }
        } else {
          this.msg.error(res.message ? res.message : '删除失败！');
        }
      });
    }
  }

  // TODO 以下功能此版本咱不实现
  rename() {
    this.msg.info('开发中');
  }

  copy() {
    this.msg.info('开发中');
  }

  move() {
    this.msg.info('开发中');
  }

  change() {
    this.msg.info('开发中');
  }
}
